export class JsUtil {
  static sleep(milliSeconds: number) {
    return new Promise((resolve) => setTimeout(resolve, milliSeconds));
  }

  static deepCopy(obj: any): any {
    return JSON.parse(JSON.stringify(obj));
  }

  static isEmail(text: string): boolean {
    return /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(text);
  }

  static isArrayEqual(source: Array<number | string>, target: Array<number | string>): boolean {
    return JSON.stringify(source) === JSON.stringify(target);
  }

  static isUnorderedArrayEqual(source: Array<number | string>, target: Array<number | string>): boolean {
    if (!(source instanceof Array) || !(target instanceof Array)) return false;
    if (source.length !== target.length) return false;

    for (var i = 0, len = target.length; i < len; i++) {
      if (source.indexOf(target[i]) === -1 && target.indexOf(source[i]) === -1) {
        return false;
      }
    }
    return true;
  }

  static scrollTo(htmlId: string) {
    // TODO optimize in the future
    const dom = document.getElementById(htmlId);
    const affix = document.getElementById('affix');
    if (affix) {
      document.documentElement.scrollTop = dom.offsetTop - affix.scrollHeight;
      return;
    }

    document.documentElement.scrollTop = dom.offsetTop;
  }

  static range(start: number, end: number): any[] {
    const range = [];
    for (let i = start; i < end; i++) {
      range.push(i);
    }
    return range;
  }

  static base64EncodeUnicode(str: string): string {
    return btoa(
      encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {
        return String.fromCharCode(Number('0x' + p1));
      })
    );
  }
}

export default JsUtil;
